# -*- coding: utf-8 -*-

import uuid,os,shutil,sys,re

import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib

#sys.path.append('/usr/lib/python2.6/dist-packages/PIL/')
#import Image

class Paginator():
    def __init__(self,allrecords,pagesize):
        if not 'all' in dir(allrecords):
            self.allrecords = allrecords
        else:
            self.allrecords = allrecords.all()
        self.pagesize = pagesize
        self.current_index = None
        self.count = None
        self.pagecount = None
        self.object_list = None
        self.hasnext = False
        self.hasprevious = False
        self.next = 1
        self.previous = 1

    def page(self, pageindex):
        self.current_index = pageindex
        self.count = len(self.allrecords)
        if self.count % self.pagesize == 0:
            if self.count == 0:
                self.pagecount=1
            else:
                self.pagecount = self.count/self.pagesize
        else:
            self.pagecount = (self.count - self.count % self.pagesize)/self.pagesize + 1

        if self.current_index != self.pagecount:
            self.hasnext = True
            self.next = self.current_index + 1
        if self.current_index != 1:
            self.hasprevious = True
            self.previous = self.current_index - 1

        self.object_list = self.allrecords[(pageindex-1)*self.pagesize:(pageindex*self.pagesize)]
        return self

    def page_from_url(self, url):
        #find the pageindex
        re_pageindex = re.compile('pageindex\d+')
        pageindex_list = re_pageindex.findall(url)
        if len(pageindex_list) > 0:
            self.page(int(pageindex_list[0].replace('pageindex','')))
        else:
            self.page(1)

def upload(requestfile, storepath, filetype={}, size=1):
    if not os.path.exists(storepath):
        os.makedirs(storepath)

    if requestfile == '':
        return ''

    filterpath = requestfile.filename.replace('\\','/').replace(' ','').replace(':','') 
    filterpath = os.path.split(filterpath)[1]
    store_file_name = os.path.splitext(filterpath)[0] + "_" + str(uuid.uuid1()).replace('-','') + os.path.splitext(filterpath)[1]
    permanent_file = open(os.path.join(storepath,store_file_name), 'wb')
    shutil.copyfileobj(requestfile.file, permanent_file)
    requestfile.file.close()
    permanent_file.close()

    return store_file_name

"""
def uploadpictures(requestfile, storepath, prefixlist, sizelist):
    original = upload(requestfile, storepath)
    if not original:
        return original

    filepath = os.path.join(storepath,os.path.split(original)[1])
    for i in range(len(sizelist)):
        width,height = sizelist[i]
        if width and height:
            image = Image.open(os.path.join(storepath,filepath))

            wantwidth = float(width)
            wantheight = float(height)

            realchange = max(image.size[0]/wantwidth, image.size[1]/wantheight)
            image = image.resize((int(image.size[0]/realchange), int(image.size[1]/realchange)))
            image.save(os.path.join(storepath,os.path.join(storepath,prefixlist[i]+os.path.split(original)[1])))
    return original
"""

def htmltagcut(source):
    re_htmltag = re.compile('<[\s\S]+?>|</[\s\S]+?>')
    return re_htmltag.sub('',source)

def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText, fromNickName=''):

        strFrom = '%s<%s>' % (fromNickName, fromAdd)
        strTo = ', '.join(toAdd)

        server = authInfo.get('server')
        user = authInfo.get('user')
        passwd = authInfo.get('password')

        if not (server and user and passwd) :
            #print 'incomplete login info, exit now'
            return

        # 设定root信息
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = subject
        msgRoot['From'] = strFrom 
        msgRoot['To'] = strTo
        msgRoot.preamble = 'This is a multi-part message in MIME format.'

        # Encapsulate the plain and HTML versions of the message body in an
        # 'alternative' part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)

        #设定纯文本信息
        msgText = MIMEText(plainText, 'plain', 'utf-8')
        msgAlternative.attach(msgText)

        #设定HTML信息
        msgText = MIMEText(htmlText, 'html', 'utf-8')
        msgAlternative.attach(msgText)

       #设定内置图片信息
        #fp = open('test.jpg', 'rb')
        #msgImage = MIMEImage(fp.read())
        #fp.close()
        #msgImage.add_header('Content-ID', '<image1>')
        #msgRoot.attach(msgImage)

       #发送邮件
        smtp = smtplib.SMTP()
       #设定调试级别，依情况而定
        smtp.set_debuglevel(1)
        smtp.connect(server)
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, strTo, msgRoot.as_string())
        smtp.quit()
        return

